package com.cans.security.browser.web;

import com.cans.security.properties.CansSecurityProperties;
import com.cans.security.properties.SecurityConstants;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author cans
 * @date 2017/11/12
 * @description 登陆登出WEB层
 */
@Controller
public class BrowserSecurityController {

    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    @Resource
    private CansSecurityProperties cansSecurityProperties;

    /**
     * 登陆
     * @param request
     * @param response
     * @return
     */
    @GetMapping(SecurityConstants.LOGOUT_URL)
    public String logout(HttpServletRequest request, HttpServletResponse response){
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth != null){
            new SecurityContextLogoutHandler().logout(request, response, auth);
        }
        return cansSecurityProperties.getBrowser().getLoginPage();
    }

    /**
     * 登出
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(SecurityConstants.TO_LOGIN)
    public String toLogout(HttpServletRequest request, HttpServletResponse response){

        return cansSecurityProperties.getBrowser().getLoginPage();
    }

}
